using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace IFXplus.SmartStorage.Utils
{
    public static class BinarySerializer
    {
        
        #region Serialization

        public static void Serialize(Stream stream, object value)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, value);
        }

        public static void Serialize(FileInfo file, object value)
        {
            FileStream stream = null;
            try
            {
                stream = File.Create(file.FullName);
                Serialize(stream, value);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }
                
        #endregion

        #region Deserialization

        public static object Deserialize(Stream stream)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            return formatter.Deserialize(stream);
        }

        public static object Deserialize(FileInfo file)
        {
            FileStream stream = null;
            try
            {
                stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
                return Deserialize(stream);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }

        #endregion

    }
}